//
//  XYEmoticonKeyBoard.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/6.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit
private let composeEmoticonCellID = "composeEmoticonCellID"
class XYEmoticonKeyBoard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    private func setUpUI() {
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        // 添加toolBar
        addSubview(toolBar)
        addSubview(emoticonView)
        addSubview(pageControl)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.bottom.equalTo(self)
            make.width.equalTo(self)
        }
        emoticonView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top)
            make.top.equalTo(self)
            make.trailing.equalTo(self)
            make.leading.equalTo(self)
        }
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        /// 主队列异步
        /// 主线程会在执行完其他任务之后再执行我们添加的任务
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
                self.emoticonView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            }
        }
    }
    // MARK: 懒加载控件
    private lazy var pageControl: UIPageControl = {
        
        let pageControl = UIPageControl()
        // 关闭用户交互，让其不能点
        pageControl.userInteractionEnabled = false
        // 选中的图片
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKeyPath: "_currentPageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKeyPath: "_pageImage")
        return pageControl
    }()
    private lazy var emoticonView: XYComposeEmoticonView = {
        let emoticonView = XYComposeEmoticonView()
        emoticonView.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        emoticonView.delegate = self
        emoticonView.dataSource = self
        emoticonView.registerClass(XYComposeEmoticonCell.self, forCellWithReuseIdentifier: composeEmoticonCellID)
        return emoticonView
    }()
    private lazy var toolBar: XYEmoticonToolBar = {
        let toolBar = XYEmoticonToolBar(frame: CGRectZero)
        toolBar.delegate = self
        return toolBar
    }()
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
extension XYEmoticonKeyBoard: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return XYEmoticonTool.sharedEmoticonTool.allEmoticons[section].count
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return XYEmoticonTool.sharedEmoticonTool.allEmoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(composeEmoticonCellID, forIndexPath: indexPath) as! XYComposeEmoticonCell
        cell.indexPath = indexPath
        let emoticons = XYEmoticonTool.sharedEmoticonTool.allEmoticons[indexPath.section][indexPath.item]
        cell.emoticons = emoticons
        return cell
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        // 取出同时显示的两个cell
        let cells = emoticonView.visibleCells()
        if cells.count == 2 {
            let firstCell = cells.first!
            let secondCell = cells.last!
            // 取出 cell的x值减去offsetX 的绝对值
            let firstX = abs(Int32(firstCell.frame.origin.x - scrollView.contentOffset.x))
            let secondX = abs(Int32(secondCell.frame.origin.x - scrollView.contentOffset.x))
            // 比较大小如果越小 显示的区域越大
            var indexPath = NSIndexPath()
            if firstX < secondX {
                indexPath = emoticonView.indexPathForCell(firstCell)!
            }else{
                indexPath = emoticonView.indexPathForCell(secondCell)!
            }
            toolBar.selectedBtnWithSection(indexPath.section)
            selectedPageControl(indexPath)
        }
        
    }
    private func selectedPageControl(indexPath: NSIndexPath){
        if indexPath.section == 0 {
            pageControl.hidden = true
        }else{
            pageControl.hidden = false
            pageControl.numberOfPages = XYEmoticonTool.sharedEmoticonTool.allEmoticons[indexPath.section].count
            pageControl.currentPage = indexPath.item
        }
    }
}
extension XYEmoticonKeyBoard: XYEmoticonToolBarDelegate {
    
    func toolBarBtnDidClickBtnType(type: EmoticonToolBarBtnType) {
        
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue - 1000)
        
        //        switch type {
        //        case .Recent:
        //            print("最近")
        //        case .Default:
        //            print("默认")
        //            indexPath = NSIndexPath(forItem: 0, inSection: 1)
        //        case .Emoji:
        //            print("emoji")
        //            indexPath = NSIndexPath(forItem: 0, inSection: 2)
        //        case .Lxh:
        //            print("浪小花")
        //            indexPath = NSIndexPath(forItem: 0, inSection: 3)
        //        }

        emoticonView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
    }
}